package org.example.recursion;

import java.util.Arrays;

/**
 * @author carol
 */
public class Fibonacci {

    /**
     * 使用记忆法进行改进 Memorization
     * @param n 代表第n项
     * @return 第n值
     */
    public static int fibonacci(int n){
        //缓存第n项
        int[] cache = new int[n+1];
        //填充-1
        Arrays.fill(cache,-1);
        cache[0] = 0;
        cache[1] = 1;

        return f(n,cache);
    }

    public static int f(int n,int[] cache){
        if(cache[n]!=-1){
            return cache[n];
        }else{
            int x = f(n - 1, cache);
            int y = f(n - 2, cache);
            cache[n] =  x + y;
            return cache[n];
        }
    }

    public static void main(String[] args) {
        System.out.println(fibonacci(10));
    }
}
